# coding=utf8
# 全世界最帅的帅哥
from flask_restful import Resource, reqparse
from comment.utils.decorators import login_required
from flask import g
from comment.modules.deal_record import DealRecord
from comment.modules.user import User
from comment.modules import db
from .serializer import DecordRecordPaginateSerializer


class DealRecordResource(Resource):
    """
    交易记录的资源类
    """

    method_decorators = [login_required]

    def get(self):
        # 交易记录列表
        rp = reqparse.RequestParser()
        rp.add_argument("startTime")  # 起始时间
        rp.add_argument("endTime")  # 结束时间
        rp.add_argument("dealType")  # 投资类型 0：全部
        rp.add_argument("curPage", required=True)  # 当前页
        rp.add_argument("perPage", required=True)  # 每一页显示数据的数量

        args = rp.parse_args()
        start_time = args.startTime
        end_time = args.endTime
        deal_type = 0 if not args.dealType else int(args.dealType)
        cur_page = args.curPage
        per_page = args.perPage

        user_id = g.user_id
        user = User.query.filter(User.id == user_id).first()
        # 得到一个查询对象
        q = DealRecord.query
        # 开始过滤
        # 1.根据交易的类型过滤
        if deal_type > 0:
            q = q.filter(DealRecord.aType == deal_type)
        # 2.对用户做过滤 普通用户只能查询自己的 role == 0 代表普通用户
        if user.role == 0:
            q = q.filter(DealRecord.aUserId == user_id)
        # 3.对时间进行过滤
        q = q.filter(db.cast(DealRecord.aDate, db.DATE) >= db.cast(start_time, db.DATE)) \
            .filter(db.cast(DealRecord.aDate, db.DATE) >= db.cast(end_time, db.DATE))
        data = q.paginate(page=cur_page, per_page=per_page, error_out=False)
        data = DecordRecordPaginateSerializer(data).to_dict()  # 转换成字典对象
        return {"msg": "success!", "data": data}
